<template>
  <div>
    <!--sticky && header-->
    <sticky>
      <x-header :left-options="{showBack: false}">注册</x-header>
    </sticky>

    <group>
      <x-input label-width="5em" title="姓名" name="username" placeholder="请输入姓名" is-type="china-name"
               v-model="name"></x-input>

      <x-input label-width="5em" title="手机" name="mobile" placeholder="请输入手机号码" keyboard="number"
               is-type="china-mobile" v-model="phone"></x-input>
    </group>

    <div style="padding:15px;">
      <x-button @click.native="register" type="primary">注册</x-button>
    </div>

  </div>

</template>

<script>
  import {
    XHeader,
    Sticky,
    Group,
    XInput,
    XButton
  } from 'vux'

  export default {
    components: {
      XHeader,
      Sticky,
      Group,
      XInput,
      XButton
    },
    data() {
      return {
        name: null,
        phone: null
      }
    },
    methods: {
      register() {
        let errTips = ''
        let canLogin = false
        const user = localStorage.getItem('USER') ? JSON.parse(localStorage.getItem('USER')) : null // 本地存储user
        if (!user.id) {
          errTips = '没有授权，请返回重试'
        } else if (!this.name) {
          errTips = '请输入姓名'
        } else if (!this.phone) {
          errTips = '请输入手机号'
        } else if (!(/^1(3|4|5|7|8)\d{9}$/).test(this.phone)) {
          errTips = '请填写正确的手机号'
        } else {
          canLogin = true
        }

        if (canLogin) {
          this.$http.post('/api/user/reg', {
            id: user.id,
            name: this.name,
            phone: this.phone,
            password: '123456'
          }).then(() => {
            this.$http.post('/api/oauth/token', {
              username: this.phone,
              password: '123456',
              grant_type: 'password',
              client_id: '2',
              client_secret: 'tJj751OklqlbfI95pjpLMH7aAQFVb5H2Qhs6xgiR'
            }).then((r) => {
              localStorage.setItem('token', r.data.token_type + ' ' + r.data.access_token)
              const url = this.$route.query.url
              url ? this.$router.push(url) : WeixinJSBridge.call('closeWindow')
            })
          })
        } else {
          this.$vux.toast.text(errTips)
        }
      }
    }
  }
</script>

<style scoped>
</style>
